package cn.com.zhbs.netty.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

public class SocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    public static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        // 打印接收到的消息
        System.out.println("服务端接受到的消息:" + textWebSocketFrame.text());
        // 返回消息给客户端
        channels.writeAndFlush(new TextWebSocketFrame(textWebSocketFrame.text()));
    }

    /**
     * 客户端连接的时候触发
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("新客户端连接："+ctx.channel().remoteAddress());
        channels.add(ctx.channel());
    }

    /**
     * 客户端断开连接的时候触发
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerRemoved：" + ctx.channel().id().asLongText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常发生了...");
        ctx.close();
    }

}
